package com.utils;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

/**
 * @author : wilbur.yuan
 * @date : 2019-04-16
 */
public class VelocityParserUtil {

    private static VelocityParserUtil instance = new VelocityParserUtil();

    private VelocityEngine engine = null;

    private VelocityParserUtil() {
        // init engine
        engine = new VelocityEngine();
        try {
            engine.init();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 返回VelocityParserUtil实例
     * @return
     */
    public static VelocityParserUtil getInstance() {
        return instance;
    }



    /**
     * 解析velocity模板
     * @param vtl
     * @param model
     * @return String
     * @throws ParseErrorException
     * @throws MethodInvocationException
     * @throws ResourceNotFoundException
     * @throws IOException
     */
    public String parseVelocityTemplate(String vtl, Map model, String logTag)
            {
//        System.out.println("parseVelocityTemplate(String, Map) - start"); //$NON-NLS-1$

        VelocityContext velocityContext = new VelocityContext(model);
        StringWriter result = new StringWriter();
        engine.evaluate(velocityContext, result, logTag, vtl);

        String returnString = result.toString();
//        System.out.println("parseVelocityTemplate(String, Map) - end"); //$NON-NLS-1$
        return returnString;

    }

}
